package com.ruoyi.stock2.thread.aboutDownloadData;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.stock2.utils.DateUtils2;
import com.ruoyi.stock2.utils.TextToPinYin;
import com.ruoyi.stock2.domain.STOCK;
import com.ruoyi.stock2.mapper.STOCKMapper;

/**
 * @author root 下载数据前，更新股票单 数据来源eastmoney 东方财富
 */
@Service
public class UpdateStocksSymbolDataService {
    private static final Logger log = LoggerFactory.getLogger(UpdateStocksSymbolDataService.class);
    @Autowired(required = false)
    STOCKMapper stockMapper;

    public Integer updateStocksSymbolData() {
        Integer Ok = null;

        List<STOCK> stocks = stockMapper.selectSTOCKList(null);
        Map<String, String> m = new HashMap<String, String>();
        for (int i = 0; i < stocks.size(); i++) {
            m.put(stocks.get(i).getSymbol(), stocks.get(i).getName());
        }

        int msg = 0;


        for (int i = 1; i < 300; i++) {
            Document doc = StocksSymbolData(i);
            if (doc == null) {
                break;
            }
            Element e = doc.body();
            JSONObject obj = JSONObject.parseObject(e.text());
            JSONObject data = (JSONObject) obj.get("data");
            if (data == null) {
                break;
            }
            Ok = msg;
            JSONArray jdiff = (JSONArray) data.get("diff");

            log.info("对比股票单还有："+(300 - i));

            for (int j = 0; j < jdiff.size(); j++) {
                JSONObject s = (JSONObject) jdiff.get(j);

                String symbol = s.get("f12").toString();
                String name = s.get("f14").toString().replace("Ａ", "A").replaceAll(" ", "");
                if (m.get(symbol) == null) {
                    STOCK stock = new STOCK();
                    stock.setName(name);
                    stock.setSymbol(symbol);
                    stock.setStatus(DateUtils2.formatDateToString(new Date(), "yyyy-MM-dd") + " 新增");
                    log.info("《《《《新增股票：代码" + symbol + ",名称：" + name);
                    String a = TextToPinYin.toPinYin(stock.getName().replace("*ST", "").replace("ST", "")
                            .replace("S", "").replace("XD", "").replace("Ａ", "A").toLowerCase());
                    stock.setPinyin(a);
                    try {
                        stockMapper.insertSTOCK(stock);
                        m.put(symbol, name);
                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }

                    msg++;
                    Ok = msg;

                } else {
                    if (!m.get(symbol).equals(name)) {
                        STOCK stock = new STOCK();
                        stock.setName(name);
                        stock.setSymbol(symbol);
                        stock.setStatus(DateUtils2.formatDateToString(new Date(), "yyyy-MM-dd") + " 更新,曾用名:"
                                + m.get(symbol));
                        log.info("《《《《更新股票：代码" + symbol + ",名称：" + name + ",曾用名:" + m.get(symbol));
                        String a = TextToPinYin.toPinYin(stock.getName().replace("*ST", "").replace("ST", "")
                                .replace("S", "").replace("XD", "").replace("Ａ", "A").toLowerCase());
                        stock.setPinyin(a);
                        stockMapper.updateSTOCK(stock);
                        msg++;
                        Ok = msg;
                    }
                }

            }

        }


        return Ok;
    }


    private Document StocksSymbolData(int i) {

        Document doc = null;
        try {
            String url = "http://10.push2.eastmoney.com/api/qt/clist/get?pn=" + i
                    + "&pz=20&po=1&np=1&fltt=2&invt=2&fid=f3&fs=m:0+t:6,m:0+t:13,m:0+t:80,m:1+t:2,m:1+t:23&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f12,f13,f14,f15,f16,f17,f18,f20,f21,f23,f24,f25,f22,f11,f62,f128,f136,f115,f152";
            // String url = "http://quote.eastmoney.com/stocklist.html";
            doc = Jsoup.parse(new URL(url).openStream(), "UTF-8", url);
            Thread.sleep(2000);
        } catch (IOException e) {
            log.error("java.net.SocketTimeoutException: Read timed out");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return doc;
    }


}
